const baseURL = "http://127.0.0.1:3000";

// 对象转字符串
function qsString(params) {
  return Object.entries(params)
    .reduce((str, el) => {
      str += `${el[0]}=${el[1]}&`;
      return str;
    }, "")
    .slice(0, -1);
}

// 添加记录 axios
export const addTodoApi = (data) => {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open("POST", `${baseURL}/todo`);
    xhr.responseType = "json";
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.onload = () => {
      resolve(res.response);
    };
    xhr.send(JSON.stringify(data));
  });
};
// 获取列表，过滤
export const getTodoListsApi = (params = {}) =>
  new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open("GET", `${baseURL}/todo?${qsString(params)}`);
    xhr.responseType = "json";
    xhr.onload = () => {
      resolve(xhr.response); // 成功
    };
    xhr.onerror = () => {
      reject(new Error("...")); // 发生错误
    };
    xhr.send();
  });
// 删除数据
export const deleteTodoApi = (id) => {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open("DELETE", `${baseURL}/todo/${id}`);
    xhr.responseType = "json";
    xhr.onload = () => {
      resolve(xhr.response);
    };
    xhr.send();
  });
};
// 修改数据
export const updateTodoApi = (id, data) => {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open("PATCH", `${baseURL}/todo/${id}`);
    xhr.responseType = "json";
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.onload = () => {
      resolve(xhr.response);
    };
    xhr.send(JSON.stringify(data));
  });
};
